/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.apiserver.http;

import org.openislands.oi.apiserver.app.RouteService;
import org.openislands.oi.pojo.dto.RouteDTO;
import org.openislands.oi.pojo.qo.NodeRouteQO;
import org.openislands.oi.pojo.qo.RouteUpdateQO;
import org.openislands.oi.pojo.vo.CommonResponse;
import org.openislands.oi.pojo.vo.NodeRouteVO;
import org.openislands.oi.util.ValueCopyUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@SuppressWarnings("unused")
@RestController
@RequestMapping(value = "/v1/routes")
public class RouteController {
    @Resource(type = RouteService.class)
    private RouteService routeService;

    @PostMapping("/")
    public CommonResponse<Boolean> addRoute(@Validated @RequestBody NodeRouteQO nodeRouteQO) {
        final RouteDTO routeDTO = ValueCopyUtils.copyProperties(nodeRouteQO, new RouteDTO());
        Boolean bool = routeService.addRoute(routeDTO);
        return CommonResponse.success(bool);
    }

    @DeleteMapping("/{id}")
    public CommonResponse<Boolean> deleteRoute(@PathVariable(value = "id") Long id) {
        final RouteDTO routeDTO = new RouteDTO();
        routeDTO.setId(id);
        Boolean bool = routeService.deleteById(routeDTO);
        return CommonResponse.success(bool);
    }

    @PutMapping("/")
    public CommonResponse<Boolean> updateRoute(@Validated @RequestBody RouteUpdateQO routeUpdateQO) {
        final RouteDTO routeDTO = ValueCopyUtils.copyProperties(routeUpdateQO, new RouteDTO());
        Boolean result = routeService.updateRoute(routeDTO);
        return CommonResponse.success(result);
    }

    @GetMapping("/{nodeId}")
    public CommonResponse<List<NodeRouteVO>> queryByNodeId(@PathVariable(value = "nodeId") String nodeId) {
        List<RouteDTO> dtoList = routeService.queryByNodeId(nodeId);
        return CommonResponse.success(ValueCopyUtils.copyList(dtoList,
                dto -> ValueCopyUtils.copyProperties(dto, new NodeRouteVO())));
    }
}
